package com.kitty.game.mount.service;

import com.kitty.game.base.service.BagService;
import com.kitty.game.enter.RespDisappear;
import com.kitty.game.fight.service.BroadcastService;
import com.kitty.game.i18n.I18nId;
import com.kitty.game.i18n.I18nIdDataPool;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.role.model.Role;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.model.RoleEquipField;
import com.kitty.game.config.PetSet;
import com.kitty.game.config.SpecialItem;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.attribute.AttrService;
import com.kitty.game.bag.message.RespIconCartoon;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.RespUpdate;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.mount.message.ReqSubmitMultiItem;
import com.kitty.game.mount.message.ReqZhaohuan;
import com.kitty.game.mount.message.RespSummonMountNotify;
import com.kitty.game.mount.message.RespSummonMountResult;
import com.kitty.game.onlinemall.service.MallService;
import com.kitty.game.pet.PetDataPool;
import com.kitty.game.pet.bean.PetObject;
import com.kitty.game.pet.message.RespPetHost;
import com.kitty.game.pet.service.PetService;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.utils.Const;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import org.apache.mina.core.session.IoSession;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Lang;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//后加
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;
import java.util.Set;

@Service
public class MountService {
    Logger logger = LoggerFactory.getLogger(MountService.class);
    @Autowired
    RoleService roleService;
    @Autowired
    EquipService equipService;
    @Autowired
    PetService petService;
    @Autowired
    AttrService attrService;

    public void submitMultiItem(IoSession session, ReqSubmitMultiItem submitMultiItem) {
        int currTime = new Long(new Date().getTime() / 1000).intValue();
        Role role = SessionUtils.getRoleBySession(session);
        int mountId = submitMultiItem.getMountId();
        List<Integer> list = submitMultiItem.getList();
        int limitNum = 0;
        RoleEquip temp = null;
        try {
            for (Integer integer : list) {
                RoleEquip equip = equipService.getEquipById(role, integer);
                temp = equip;
                if (equip.queryNum() < 1) {
                    return;
                }
                boolean isLimit = false;
                if (equip.isEverLimit()) {
                    isLimit = true;
                }
                limitNum += equipService.delRoloEquip(equip.getName(), 1, isLimit, session);
            }
        } catch (Exception e) {
            logger.error("驯化坐骑报错==={}=={}=={}=={}", Lang.getStackTrace(e), (temp == null ? "物品为空" : temp.getName()), role.getName(), Json.toJson(submitMultiItem, JsonFormat.compact()));
        }


        Pet pet = petService.getPetById(mountId, role);
        pet.setItype((byte) 2);
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(mountId);
        respUpdate.setList(new ArrayList<>());
        if (limitNum >= 1) {
            petService.addLimitTime(pet, limitNum);
            FiedValue fiedValue = new FiedValue();
            fiedValue.setType((short) 270);  //限制交易
            fiedValue.setVT((byte) 3);
            fiedValue.setValue(pet.getLimitTime());
            respUpdate.getList().add(fiedValue);

        }
        pet.setMountTime(currTime + 86400 * 30);
        FiedValue fiedValue = new FiedValue();
        fiedValue.setType((short) 294);
        fiedValue.setVT((byte) 1);
        fiedValue.setValue(pet.getItype());
        respUpdate.getList().add(fiedValue);
        MessagePusher.pushMessage(session, respUpdate);
        petService.refreshPetInfo(role, pet);
        roleService.addAchieveScore(role,"201034");
        role.save();

        MessagePusher.pushMessage(session, new RespNotifyMiscEx("#R" + pet.getName() + "#n驯化完成。"));
    }
    //召唤坐骑
    private String getRandom(boolean boo) {
        Random random = new Random();
        int total = 0;
        Set<String> set = DataCache.MOUNTS;
        for (String name : set) {
            short icon = DataCache.NAME_ICON.get(name);
            PetSet petSet = DataCache.ICON_PETSET.get(icon);
            total = total + (boo ? petSet.getPersent() : petSet.getPersent1());
        }
        int result = random.nextInt(total) + 1;
        String resultName = null;
        total = 0;
        for (String name : set) {
            short icon = DataCache.NAME_ICON.get(name);
            PetSet petSet = DataCache.ICON_PETSET.get(icon);
            total = total + (boo ? petSet.getPersent() : petSet.getPersent1());
            if (result <= total) {
                return name;
            }
        }
        return resultName;

    }

    public void zhaohuan(IoSession session, ReqZhaohuan reqZhaohuan) {
        Role role = SessionUtils.getRoleBySession(session);


        int DBMoney = role.getMoney();
        if (reqZhaohuan.getFlag() == 5) {
            int money = 500 * 10000;
            if (DBMoney < money) {
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("金钱不足"));
                return;
            }
            int count = equipService.getCount("精怪诱饵", true, role);
            if (count < 1) {
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("精怪诱饵不足"));
                return;
            }

            RespSummonMountResult respSummonMountResult = new RespSummonMountResult();
            respSummonMountResult.setType((byte)5);///reqZhaohuan.getFlag()
            String name = "1";//getRandom(true);
            respSummonMountResult.setName(name);
            MessagePusher.pushMessage(session, respSummonMountResult);
            session.setAttribute(Const.zuoqiChoujiang, name);
        }else if (reqZhaohuan.getFlag() == 6) {
            int money = 5000 * 10000;
            if (DBMoney < money) {
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("金钱不足"));
                return;
            }
            int count = equipService.getCount("精怪诱饵", true, role);
            if (count < 10) {
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("精怪诱饵不足"));
                return;
            }

            RespSummonMountResult respSummonMountResult = new RespSummonMountResult();
            respSummonMountResult.setType(reqZhaohuan.getFlag());
            String name = "1";//getRandom(true);
            respSummonMountResult.setName(name);
            MessagePusher.pushMessage(session, respSummonMountResult);
            session.setAttribute(Const.zuoqiChoujiang, name);

        }  else if (reqZhaohuan.getFlag() == 1) {
            int money = 500 * 10000;
            equipService.delRoloEquip("精怪诱饵", 1, true, role);
            roleService.subtractMoney(role,  money);//这里可能是重复检测金钱的地方

            PetService petService = SpringUtils.getBean(PetService.class);

            String name = getRandom(true);
            PetObject petObject = PetDataPool.getPetObject(name);
            Pet pet = petService.addPet(petObject, role, false);
            petService.loadPet(role, pet);

            RespSummonMountNotify respSummonMountNotify = new RespSummonMountNotify();
            respSummonMountNotify.setType(reqZhaohuan.getFlag());
            respSummonMountNotify.setId(pet.getId());
            MessagePusher.pushMessage(session, respSummonMountNotify);



            RespSummonMountResult respSummonMountResult = new RespSummonMountResult();
            respSummonMountResult.setType(reqZhaohuan.getFlag());
            respSummonMountResult.setName("1");
            MessagePusher.pushMessage(session, respSummonMountResult);


        }else if ( reqZhaohuan.getFlag() == 2) {
            int money = 5000 * 10000;
            equipService.delRoloEquip("精怪诱饵", 10, true, role);
            roleService.subtractMoney(role,  money);//这里可能是重复检测金钱的地方

            BroadcastService broadcastService = SpringUtils.getBean(BroadcastService.class);
            PetService petService = SpringUtils.getBean(PetService.class);
            //Object object = session.getAttribute(Const.zuoqiChoujiang);
           // if (object == null) {
            //    return;
          //  }
            //session.removeAttribute(Const.zuoqiChoujiang);
            String name = getRandom(false);
            PetObject petObject = PetDataPool.getPetObject(name);
            Pet pet = petService.addPet(petObject, role, false);
            petService.loadPet(role, pet);
            RespSummonMountNotify respSummonMountNotify = new RespSummonMountNotify();
            respSummonMountNotify.setType(reqZhaohuan.getFlag());
            respSummonMountNotify.setId(pet.getId());
            MessagePusher.pushMessage(session, respSummonMountNotify);
            RespSummonMountResult respSummonMountResult = new RespSummonMountResult();
            respSummonMountResult.setType(reqZhaohuan.getFlag());
            respSummonMountResult.setName("1");
            MessagePusher.pushMessage(session, respSummonMountResult);
            if (pet.getRank() >= 5) {
                String notice = "传闻#R%s#n在捕捉精怪时，竟然捕捉到了隐藏在精怪之中的#R%s#n奖励，运气真是太好了！大家也快带上#R精怪诱饵#n到#P玉真子#P处捕捉精怪吧！";
                notice = String.format(notice, role.getName(), pet.getName());
                broadcastService.sendRumor(notice, null);
            }

            if (pet.getRank() >= 8) {//这里的8 不知道是干啥的
                String content = I18nIdDataPool.getI18nContent(I18nId.PMT_1900, role.getName(), pet.getRank(), pet.getName());
                SpringUtils.getChatService().sendAdnotice(content);
            }
        }
    }


    /**
     * 宠物转灵魄
     */
    public void convert(Role role, short pos) {
        Pet pet = petService.getPetByPos((byte) pos, role);
        if (pet == null) {
            return;
        }
        if (pet.getRank() > 4 || pet.getRank() < 2) {
            return;
        }
        if (role.getMoney() < 1000000) {
            MessagePusher.pushMessage(role, new RespMsg("你的金钱不足，无法转化。"));
            return;
        }
        short itemPos = SpringUtils.getBean(BagService.class).getPos(role, false);
        if (itemPos <= 0) {
            MessagePusher.pushMessage(role, new RespMsg("你的包裹已满，请整理后再来吧。"));
            return;
        }
        petService.delPet(role,pet);
        roleService.subtractMoney(role, 1000000);
        String name = pet.getRank() + "阶骑宠灵魄";
        RespPetHost respPetHost = new RespPetHost();
        respPetHost.setPetId(pet.getId());
        MessagePusher.pushMessage(role, respPetHost);
        getConvertItem(role, name, 1, itemPos);
        MessagePusher.pushMessage(role, new RespNotifyMiscEx("你将#Y" + pet.getName() + "（精怪）#n成功转化，获得了#R1个#n" + pet.getRank() + "阶骑宠灵魄。"));
    }


    /**
     * 获得骑宠灵魄
     */
    private void getConvertItem(Role role, String name, int num, short pos) {
        RoleEquip roleEquip = new RoleEquip();
        roleEquip.setId(SpringUtils.getBean(MallService.class).getRoleEquipId());
        roleEquip.setRoleId(role.getRoleId());
        roleEquip.setPosition(pos);
        roleEquip.setName(name);
        roleEquip.setFields(new LinkedHashMap<>());
        roleEquip.setType("宠物道具");
        SpecialItem specialItem = SpringUtils.getBean(MallService.class).getSpecialItem(name);
        RoleEquipField roleEquipField = new RoleEquipField();
        roleEquipField.setType((short) 1);
        LinkedHashMap<Short, FiedValue> basicAttribute = new LinkedHashMap<>();
        roleEquipField.setField(basicAttribute);
        roleEquip.getFields().put(roleEquipField.getType(), roleEquipField);
        List<FiedValue> values = new ArrayList<>();
        values.add(new FiedValue(205, 0));
        values.add(new FiedValue(206, 6));
        values.add(new FiedValue(74, 5));
        values.add(new FiedValue(40, specialItem.getIcon()));
        values.add(new FiedValue(207, 500));
        values.add(new FiedValue(1, name));
        values.add(new FiedValue(306, ""));
        values.add(new FiedValue(209, ""));
        values.add(new FiedValue(84, roleEquip.getId()));
        values.add(new FiedValue(203, num));
        values.add(new FiedValue(282, 1));
        values.forEach(value -> basicAttribute.put(value.getType(), value));
        equipService.add(role, roleEquip);
        equipService.refreshRoleEquip(role, roleEquip);
        RespIconCartoon iconCartoon = new RespIconCartoon(roleEquip.getName());
        MessagePusher.pushMessage(role, iconCartoon);
    }
}
